package com.caszx.chargingpile.activity;


import android.app.ActivityManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Color;
import android.os.Bundle;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.TextUtils;
import android.text.style.ForegroundColorSpan;
import android.text.style.RelativeSizeSpan;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.RadioGroup;
import android.widget.TextView;

import com.alibaba.fastjson.JSONException;
import com.app.base.app.BaseTopBarDelayActivity;
import com.app.jsonparse.JSONParse;
import com.app.utils.DiskUser;
import com.caszx.chargingpile.R;
import com.caszx.chargingpile.entity.EntityCommPile;
import com.caszx.chargingpile.eventbus.EventBusAction;
import com.caszx.chargingpile.http.ConstantUrl;
import com.caszx.chargingpile.utils.DialogHelp;
import com.caszx.chargingpile.utils.SnackbarHelp;
import com.nispok.snackbar.Snackbar;
import com.rey.material.app.Dialog;
import com.rey.material.app.DialogFragment;
import com.rey.material.app.SimpleDialog;

import net.simonvt.numberpicker.NumberPicker;

import org.json.JSONObject;

import java.text.DateFormat;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import de.greenrobot.event.EventBus;
import http.okhttp.OkHttpUtils;
import http.okhttp.callback.JsonCallback;
import okhttp3.Call;


/**
 * 预约支付
 * */
public class ReservatePayActivity extends BaseTopBarDelayActivity
        implements View.OnClickListener,RadioGroup.OnCheckedChangeListener{


    private String stationId;
    private String stationName;

    private TextView txt_cur_time;
    private TextView txt_hour;
    private TextView txt_minute;
    private RadioGroup radioG_day;
    private RadioGroup radioG_ac_dc;
    private TextView txt_price;
    private TextView btn_confirm;

    private DialogFragment mDialog;
    private NumberPicker hour;
    private NumberPicker minute;

    private TimeChangeRecever timeChangeRecever;
    private DateFormat formatter = new SimpleDateFormat("HH:mm");
    @Override
    protected void init() {
        stationId = getIntent().getStringExtra("ID");
        stationName = getIntent().getStringExtra("NAME");
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_reservate_pay);
        timeChangeRecever  = new TimeChangeRecever();
        IntentFilter timeChangeFilter  = new IntentFilter();
        timeChangeFilter.addAction(Intent.ACTION_TIME_TICK); //以分钟为单位，每分钟会发一次广播
        registerReceiver(timeChangeRecever, timeChangeFilter);

        setCenterTitle(stationName);
        initviewData();
        refrashPrice(0);

    }

    @Override
    protected void findView() {
        txt_cur_time = (TextView) findViewById(R.id.txt_cur_time);
        txt_hour = (TextView) findViewById(R.id.txt_hour);
        txt_minute = (TextView) findViewById(R.id.txt_minute);
        txt_price = (TextView) findViewById(R.id.txt_price);
        btn_confirm = (TextView) findViewById(R.id.btn_confirm);
        radioG_day = (RadioGroup) findViewById(R.id.radioG_day);
        radioG_ac_dc = (RadioGroup) findViewById(R.id.radioG_ac_dc);
        txt_hour.setOnClickListener(this);
        txt_minute.setOnClickListener(this);
        btn_confirm.setOnClickListener(this);
    }

    private void initviewData( ){
        Date  curDate  = new Date(System.currentTimeMillis());
        String  str  = formatter.format(curDate);
        txt_cur_time.setText("当前时间 "+str);
        int_hour = curDate.getHours();
        int_minute = curDate.getMinutes();
        radioG_day.setOnCheckedChangeListener(this);
        radioG_ac_dc.setOnCheckedChangeListener(this);

    }


    private void refrashPrice(double price){
        SpannableStringBuilder builder = new SpannableStringBuilder();
        ForegroundColorSpan foregroundColorSpan = new ForegroundColorSpan(Color.parseColor("#FFFF7700"));
        if(price>=0){
            DecimalFormat decimalFormat = new DecimalFormat("##.##");
            builder.append("预约费用\u0020").append("￥").append(decimalFormat.format(price));
        }else{
            builder.append("网络异常,无法计算预约费");
        }

        builder.setSpan(foregroundColorSpan, 0, builder.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE  );


        RelativeSizeSpan  relativeSizeSpan = new RelativeSizeSpan(0.8f);
        int start = builder.length();
        builder.append("\n\n预约费用的计费方案具体可在电站详情查看\n支付后预约立即生效");
        builder.setSpan(relativeSizeSpan, start,  builder.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        ForegroundColorSpan colorSpan = new ForegroundColorSpan(getResources().getColor(R.color.black));
        builder.setSpan(colorSpan, start,  builder.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        txt_price.setText(builder);
    }

    private void refrashPrice(String msg){
        SpannableStringBuilder builder = new SpannableStringBuilder();
        ForegroundColorSpan foregroundColorSpan = new ForegroundColorSpan(Color.parseColor("#FFFF7700"));
        builder.append(msg);
        builder.setSpan(foregroundColorSpan, 0, builder.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE  );

        RelativeSizeSpan  relativeSizeSpan = new RelativeSizeSpan(0.8f);
        int start = builder.length();
        builder.append("\n\n预约费用的计费方案具体可在电站详情查看\n支付后预约立即生效");
        builder.setSpan(relativeSizeSpan, start,  builder.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        ForegroundColorSpan colorSpan = new ForegroundColorSpan(getResources().getColor(R.color.black));
        builder.setSpan(colorSpan, start,  builder.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        txt_price.setText(builder);
    }

    private int int_hour=0;
    private int int_minute=0;

    private  void showNumberPicker(){
        if (mDialog == null) {
            Dialog.Builder builder = new SimpleDialog.Builder(
                    R.style.SimpleDialogLight) {
                @Override
                protected void onBuildDone(Dialog dialog) {
                    dialog.layoutParams( ViewGroup.LayoutParams.WRAP_CONTENT,
                            ViewGroup.LayoutParams.WRAP_CONTENT);
                    hour = (NumberPicker) dialog.findViewById(R.id.numberPicker_hour);
                    hour.setMaxValue(23);
                    hour.setMinValue(0);
                    minute = (NumberPicker) dialog.findViewById(R.id.numberPicker_minute);
                    minute.setMaxValue(59);
                    minute.setMinValue(0);
                    hour.setValue(int_hour);
                    minute.setValue(int_minute);
                }


                @Override
                public void onPositiveActionClicked(DialogFragment fragment) {
                    super.onPositiveActionClicked(fragment);
                    txt_hour.setText(hour.getValue()+"");
                    txt_minute.setText(minute.getValue()+"");
                    int_hour = hour.getValue();
                    int_minute = minute.getValue();
                    refrashPrice();
                }

                @Override
                public void onNegativeActionClicked(DialogFragment fragment) {
                    super.onNegativeActionClicked(fragment);
                }
            };

            builder.positiveAction("确定").negativeAction("取消")
                    .contentView(R.layout.layout_number_picker);
            mDialog = DialogFragment.newInstance(builder);

        }
        mDialog.show(getSupportFragmentManager().beginTransaction(), stationId);
    }

    @Override
    public void onClick(View v) {

        switch (v.getId()){
            case  R.id.txt_hour:
            case  R.id.txt_minute:
                showNumberPicker();
                break;
            case  R.id.btn_confirm:

               String hour =  txt_hour.getText().toString();
               String minute =  txt_minute.getText().toString();
                if(TextUtils.isEmpty(hour)){
                   SnackbarHelp.showSnackbarMsg(ReservatePayActivity.this,"请选择小时");
                    return;
                }
                if(TextUtils.isEmpty(minute)){
                    SnackbarHelp.showSnackbarMsg(ReservatePayActivity.this,"请选择分钟");
                    return;
                }

                confirmSubscribe();
                break;
        }
    }


    @Override
    protected void onDestroy() {
        unregisterReceiver(timeChangeRecever);
        super.onDestroy();
    }

    private void confirmSubscribe(){
        showProgressDialog("预约中");
        int date = radioG_day.getCheckedRadioButtonId() == R.id.radio_btn_today?0:1;
        int payType = 3;
        int pileType = radioG_day.getCheckedRadioButtonId() == R.id.radio_btn_ac?1:2;
        Date  curDate  = new Date(System.currentTimeMillis());
        String startTime = formatter.format(curDate);
        String endTime = txt_hour.getText().toString()+":"+txt_minute.getText().toString();
        HashMap<String,String> params = new HashMap<>();
        params.put("token", DiskUser.getStringValueByKey(this,"token"));
        params.put("date",date+"");
        params.put("startTime",startTime);
        params.put("endTime",endTime);
        params.put("stationId",stationId);
        params.put("payType",payType+"");
        params.put("pileType",pileType+"");
        OkHttpUtils.post()
                .url(ConstantUrl.URL_FEE_CONFIRM)
                .params(params)
                .tag(this)
                .build()
                .execute(new JsonCallback() {
                    @Override
                    public void onError(Call call, Exception e) {
                        dissmissProgressDialog();
                        SnackbarHelp.showSnackbarMsg(ReservatePayActivity.this,getResources().getString(R.string.error_network));
                    }
                    @Override
                    public void onResponse(JSONObject response) {
                        dissmissProgressDialog();
                        JSONObject resultJsonObject =  response.optJSONObject("result");
                        if(resultJsonObject!=null){
                            int code =  resultJsonObject.optInt("code");
                            if(code==-100){
                                DialogHelp.showDialogOnlyMesg(ReservatePayActivity.this,getResources().getString(R.string.error_minus_100), new DialogHelp.DialogActionClickListener() {
                                    @Override
                                    public void onPositiveActionClicked(DialogFragment fragment) {
                                        Intent intent = new Intent(ReservatePayActivity.this,UserSignInActivity.class);
                                        startActivity(intent);
                                    }

                                    @Override
                                    public void onNegativeActionClicked(DialogFragment fragment) {
                                    }
                                });
                                return;
                            }
                            if(code<0){
                                //error
                                 DialogHelp.showDialogOnlyMesg(ReservatePayActivity.this,resultJsonObject.optString("msg"),null);
                            }else{
                                try {
                                     DialogHelp.showDialogOnlyMesg(ReservatePayActivity.this,"确定",null, resultJsonObject.optString("msg"), new DialogHelp.DialogActionClickListener() {
                                         @Override
                                         public void onPositiveActionClicked(DialogFragment fragment) {
                                             EventBus.getDefault().post(EventBusAction.ACTION_USER_SUCCESS_RESER);
                                             ReservatePayActivity.this.finish();
                                         }
                                         @Override
                                         public void onNegativeActionClicked(DialogFragment fragment) { }
                                     });
                                }catch (JSONException e){
                                    SnackbarHelp.showSnackbarMsg(ReservatePayActivity.this,getResources().getString(R.string.error_parser_json));
                                }
                            }
                        }
                    }
                });
    }

    private void refrashPrice(){

        showProgressDialog("");
        int date = radioG_day.getCheckedRadioButtonId() == R.id.radio_btn_today?0:1;
        Date  curDate  = new Date(System.currentTimeMillis());
        String startTime = formatter.format(curDate);
        String endTime = txt_hour.getText().toString()+":"+txt_minute.getText().toString();
        HashMap<String,String> params = new HashMap<>();
        params.put("token", DiskUser.getStringValueByKey(this,"token"));
        params.put("date",date+"");
        params.put("startTime",startTime);
        params.put("endTime",endTime);
        params.put("stationId",stationId);
        OkHttpUtils.post()
                .url(ConstantUrl.URL_FEE_TIME)
                .params(params)
                .tag(this)
                .build()
                .execute(new JsonCallback() {
                    @Override
                    public void onError(Call call, Exception e) {
                        dissmissProgressDialog();
                        refrashPrice(-1);
                        SnackbarHelp.showSnackbarMsg(ReservatePayActivity.this,getResources().getString(R.string.error_network));
                    }

                    @Override
                    public void onResponse(JSONObject response) {
                        dissmissProgressDialog();
                        JSONObject resultJsonObject =  response.optJSONObject("result");
                        if(resultJsonObject!=null){
                            int code =  resultJsonObject.optInt("code");
                            if(code<0){
                                //error
                                refrashPrice(resultJsonObject.optString("msg"));
                                // DialogHelp.showDialogOnlyMesg(resultJsonObject.optString("msg"),null);
                            }else{
                                try {
                                    double beforeFee = response.optDouble("beforeFee");
                                    refrashPrice(beforeFee);
                                }catch (JSONException e){
                                    SnackbarHelp. showSnackbarMsg(ReservatePayActivity.this,getResources().getString(R.string.error_parser_json));
                                }
                            }
                        }
                    }
                });
    }

    @Override
    public void onCheckedChanged(RadioGroup group, int checkedId) {
        if(checkedId == R.id.radio_btn_today||checkedId == R.id.radio_btn_tomorrow){
            String hour =  txt_hour.getText().toString();
            String minute =  txt_minute.getText().toString();
            if(TextUtils.isEmpty(hour)){

                return;
            }
            if(TextUtils.isEmpty(minute)){

                return;
            }
            refrashPrice();
        }

    }

    private class TimeChangeRecever extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            Date curDate = new Date(System.currentTimeMillis());
            String str = formatter.format(curDate);
            int_hour = curDate.getHours();
            int_minute = curDate.getMinutes();
            txt_cur_time.setText("当前时间 "+str);
        }
    }
}
